package com.honghe.aop;

import com.honghe.constant.JwtClaimsConstant;
import com.honghe.constant.MessageConstant;
import com.honghe.context.BaseContext;
import com.honghe.entity.Doctor;
import com.honghe.exception.VerifyException;
import com.honghe.mapper.DoctorMapper;
import com.honghe.properties.JwtProperties;
import com.honghe.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class VerifyAspect {
    /*@Autowired
    private DoctorMapper doctorMapper;*/
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    //在controller层进行更新(update)，插入(insert)，删除(delete)操作的校验
    //请一定注重命名规范
    @Pointcut("execution(* com.honghe.controller.*.update(..)) ||" +
            "execution(* com.honghe.controller.*.insert*(..)) ||" +
            "execution(* com.honghe.controller.*.delete(..))")
    private void verify() {}
    @Before("verify()")
    public void doVerify() {
        //删除所有科室和医生的缓存
        redisTemplate.delete("deptWithDoc::SimpleKey []");
        //通过请求头部获取信息
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        Integer docJob = Integer.valueOf(claims.get(JwtClaimsConstant.DOC_JOB).toString());
        if (docJob > 2){
            throw new VerifyException(MessageConstant.VERIFY_ERROR);
        }
        /*//Plan B 操作数据库获取信息
        //获取医生的id
        Long docId = BaseContext.getCurrentId();
        //获取到该医生
        Doctor doctor = doctorMapper.getById(docId);
        //获取医生职位
        Integer job = doctor.getJob();
        if (job > 2){
            throw new VerifyException(MessageConstant.VERIFY_ERROR);
        }*/
    }
}
